package org.system.core.service.system;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.system.core.common.Constants;
import org.system.core.domain.entity.SysMenu;
import org.system.core.domain.entity.SysRole;
import org.system.core.domain.entity.SysUser;
import org.system.core.domain.model.TreeSelect;
import org.system.core.domain.vo.MetaVo;
import org.system.core.domain.vo.RouterVo;
import org.system.core.exception.ServiceException;
import org.system.core.mapper.system.SysMenuMapper;
import org.system.core.mapper.system.SysRoleMapper;
import org.system.core.mapper.system.SysRoleMenuMapper;
import org.system.core.utils.MessageUtils;
import org.system.core.utils.SecurityUtils;
import org.system.core.utils.StringUtil;
import org.system.core.utils.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author baoRoot
 */
@Service
public class SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    public SysMenu selectMenuById(Long menuId) {
        return sysMenuMapper.selectMenuById(menuId);
    }

    public List<SysMenu> selectMenuList(Long userId) {
        return selectMenuList(new SysMenu(), userId);
    }

    public List<Long> selectMenuListByRoleId(Long roleId) {
        if (roleId == null) {
            throw new ServiceException(MessageUtils.message("system.role.no_id"));
        }
        SysRole role = sysRoleMapper.selectRoleById(roleId);
        return sysMenuMapper.selectMenuListByRoleId(roleId, role.isMenuCheckStrictly());
    }

    public boolean checkMenuNameUnique(SysMenu menu) {
        Long menuId = StringUtils.isNull(menu.getMenuId()) ? -1L : menu.getMenuId();
        SysMenu info = sysMenuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId());
        return !StringUtils.isNotNull(info) || info.getMenuId().longValue() == menuId.longValue();
    }

    public void beforeVerify(SysMenu menu, boolean isUpdate) {
        if(!checkMenuNameUnique(menu)) {
            throw new ServiceException(MessageUtils.message("system.menu.name_error"));
        }
        if(Constants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtil.ishttp(menu.getPath())) {
            throw new ServiceException(MessageUtils.message("system.menu.http_error"));
        }
        if(isUpdate && menu.getMenuId().equals(menu.getParentId())) {
            throw new ServiceException(MessageUtils.message("system.menu.superiors_error"));
        }
    }

    public void beforeVerify(SysMenu menu) {
        beforeVerify(menu, false);
    }

    public void insertMenu(SysMenu menu) {
        beforeVerify(menu);
        menu.setCreateBy(SecurityUtils.getUsername());
        if (sysMenuMapper.insertMenu(menu) <= 0) {
            throw new ServiceException(MessageUtils.message("system.monitor.add_error"));
        }
    }

    public boolean hasChildByMenuId(Long menuId) {
        int result = sysMenuMapper.hasChildByMenuId(menuId);
        return result > 0;
    }

    public boolean checkMenuExistRole(Long menuId) {
        int result = sysRoleMenuMapper.checkMenuExistRole(menuId);
        return result > 0;
    }

    public void deleteMenu(Long menuId) {
        if(menuId == null) {
            throw new ServiceException(MessageUtils.message("system.menu.no_id"));
        }
        if(hasChildByMenuId(menuId)) {
            throw new ServiceException(MessageUtils.message("system.menu.next_error"));
        }
        if(checkMenuExistRole(menuId)) {
            throw new ServiceException(MessageUtils.message("system.menu.use_error"));
        }
        if(sysMenuMapper.deleteMenuById(menuId) <= 0) {
            throw new ServiceException(MessageUtils.message("system.monitor.delete_error"));
        }
    }

    public void updateMenu(SysMenu menu) {
        beforeVerify(menu, true);
        menu.setUpdateBy(SecurityUtils.getUsername());
        if(sysMenuMapper.updateMenu(menu) <= 0) {
            throw new ServiceException(MessageUtils.message("system.monitor.update_error"));
        }
    }

    public List<SysMenu> selectMenuList(SysMenu menu, Long userId) {
        List<SysMenu> menuList = null;
        // 管理员显示所有菜单信息
        if (SysUser.isAdmin(userId)) {
            menuList = sysMenuMapper.selectMenuList(menu);
        } else {
            menu.getParams().put("userId", userId);
            menuList = sysMenuMapper.selectMenuListByUserId(menu);
        }
        return menuList;
    }

    public List<SysMenu> buildMenuTree(List<SysMenu> menus) {
        List<SysMenu> returnList = new ArrayList<>();
        List<Long> tempList = menus.stream().map(SysMenu::getMenuId).collect(Collectors.toList());
        for (SysMenu menu : menus) {
            if (!tempList.contains(menu.getParentId())) {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()) {
            returnList = menus;
        }
        return returnList;
    }

    public List<TreeSelect> buildMenuTreeSelect(List<SysMenu> menus) {
        List<SysMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    public Set<String> selectMenuPermsByRoleId(Long roleId) {
        List<String> perms = sysMenuMapper.selectMenuPermsByRoleId(roleId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    public Set<String> selectMenuPermsByUserId(Long userId) {
        List<String> perms = sysMenuMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }

    public List<SysMenu> selectMenuTreeByUserId(Long userId) {
        List<SysMenu> menus = null;
        if (SecurityUtils.isAdmin(userId)) {
            menus = sysMenuMapper.selectMenuTreeAll();
        } else {
            menus = sysMenuMapper.selectMenuTreeByUserId(userId);
        }
        return getChildPerms(menus, 0);
    }

    public List<SysMenu> getChildPerms(List<SysMenu> list, int parentId) {
        List<SysMenu> returnList = new ArrayList<>();
        for (SysMenu t : list) {
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    private void recursionFn(List<SysMenu> list, SysMenu t) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    private boolean hasChild(List<SysMenu> list, SysMenu t) {
        return !getChildList(list, t).isEmpty();
    }

    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) {
        List<SysMenu> tlist = new ArrayList<>();
        for (SysMenu n : list) {
            if (n.getParentId().longValue() == t.getMenuId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    public List<RouterVo> buildMenus(List<SysMenu> menus) {
        List<RouterVo> routers = new LinkedList<>();
        for (SysMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtil.equals("1", menu.getIsCache()), menu.getPath()));
            List<SysMenu> cMenus = menu.getChildren();
            if (StringUtils.isNotEmpty(cMenus) && Constants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtil.capitalize(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), StringUtil.equals("1", menu.getIsCache()), menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(Constants.INNER_LINK);
                children.setName(StringUtil.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    public String getComponent(SysMenu menu) {
        String component = Constants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = Constants.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = Constants.PARENT_VIEW;
        }
        return component;
    }

    public boolean isParentView(SysMenu menu) {
        return menu.getParentId().intValue() != 0 && Constants.TYPE_DIR.equals(menu.getMenuType());
    }

    public String getRouterPath(SysMenu menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && Constants.TYPE_DIR.equals(menu.getMenuType())
                && Constants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        } else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    public String innerLinkReplaceEach(String path) {
        return StringUtil.replaceEach(path, new String[] { Constants.HTTP, Constants.HTTPS, Constants.WWW, ".", ":" },
                new String[] { "", "", "", "/", "/" });
    }

    public boolean isInnerLink(SysMenu menu) {
        return menu.getIsFrame().equals(Constants.NO_FRAME) && StringUtil.ishttp(menu.getPath());
    }

    public String getRouteName(SysMenu menu) {
        String routerName = StringUtil.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtil.EMPTY;
        }
        return routerName;
    }

    public boolean isMenuFrame(SysMenu menu) {
        return menu.getParentId().intValue() == 0 && Constants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(Constants.NO_FRAME);
    }

}
